package com.qk.management.aop;

import cn.hutool.json.JSONUtil;
import com.qk.common.Result;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: Enid
 * @date: 2025/10/17 17:21
 * @description:
 */
@Slf4j
@Aspect
@Component
public class LogRecordAspect {
    @Autowired
    private OperateLogMapper  operateLogMapper;

    //定义切点
    @Pointcut("@annotation(com.qk.management.aop.anno.LogAnno)")
    public void pt(){}

    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) {
        Object returnValue = null;
        try {
            long start = System.currentTimeMillis();
           returnValue = pjp.proceed();

           long end = System.currentTimeMillis();
           log.info("耗时：{}",end-start);
            Integer userId = CurrentUserContextHolders.get();
            String className = pjp.getTarget().getClass().getName();
            String methodName = pjp.getSignature().getName();
            Object[] args = pjp.getArgs();
            String methodParams = JSONUtil.toJsonStr(args);
            String returnValueStr = JSONUtil.toJsonStr(returnValue);
            OperateLog operateLog = OperateLog.builder()
                    .className(className)
                    .methodName(methodName)
                    .methodParams(methodParams)
                    .returnValue(returnValueStr)
                    .costTime(end-start)//耗时
                    .operateUserId(userId)
                    .build();
            try {
                operateLogMapper.insert(operateLog);
            } catch (Exception e) {
                log.error("日志插入失败:{}",e.getMessage());
            }

        } catch (Throwable e) {
            returnValue= Result.error("操作失败,请稍后重试");
            log.error("操作失败:{}",e.getMessage());
        }
        return returnValue;
    }
}
